package com.pac.user.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.common.page.Page;
import com.common.page.PageContext;
import com.common.tools.MD5Tools;
import com.common.tools.StringTools;
import com.common.util.LogicException;
import com.common.util.SessionKeyContent;
import com.pac.role.bean.RoleBean;
import com.pac.role.bean.RoleUserRelBean;
import com.pac.role.service.RoleUserRelService;
import com.pac.user.bean.UserBean;
import com.pac.user.bean.UserDetailBean;
import com.pac.user.service.UserDetailService;
import com.pac.user.service.UserService;
import com.pac.weixin.bean.WxDoctorSelBean;
import com.pac.weixin.service.WxDoctorSelService;

/**
 * 用户Controller
 * 
 * @author lujun.chen
 * @version [版本号, 2015年2月13日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Controller
@Scope("prototype")
@RequestMapping("/user")
public class UserController {

	private static Logger logger = Logger.getLogger(UserController.class);

	@Autowired
	private UserService userService;

	@Autowired
	private RoleUserRelService roleUserRelService;

	@Autowired
	private WxDoctorSelService wxDoctorSelService;

	@Autowired
	private UserDetailService userDetailService;

	/**
	 * 检查用户名是否存在 修改前后用户名未改变说明用户名未改，还是原来的名字，无需验证
	 * 
	 * @param username
	 *            需要检查的用户名
	 * @param userNameOld
	 *            修改前的用户名
	 * @return true 系统存在该用户名 false 系统不存在该用户名
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/exist")
	@ResponseBody
	public boolean usernameExist(String username, String userNameOld) {
		if (username.equals(userNameOld)) {
			return false;
		}
		UserBean userBean = new UserBean();
		userBean.setUserName(username);

		UserBean userBeanR = userService.findUser(userBean);
		if (null != userBeanR) {
			return true;
		}

		return false;
	}

	/**
	 * 检查用户名密码 检查用户名密码是否正确
	 * 
	 * @param username
	 * @param password
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/checkPassword")
	@ResponseBody
	public boolean checkPassword(HttpServletRequest request, String username,
			String password) {
		if (StringTools.isNull(username)) {
			return false;
		}
		if (StringTools.isNull(password)) {
			return false;
		}

		String passwordMD5 = MD5Tools.MD5(password);
		passwordMD5 = passwordMD5.toLowerCase();

		logger.info("检查密码，username：" + username + ",password:" + passwordMD5);

		UserBean userBean = new UserBean();
		userBean.setUserName(username);
		userBean.setPassword(passwordMD5);
		UserBean userBeanR = userService.findUser(userBean);
		if (null != userBeanR) {
			return true;
		}

		return false;
	}

	/**
	 * 用户列表查询
	 * 
	 * @param userBean
	 * @param page
	 * @param rows
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/listData")
	@ResponseBody
	public Page queryUserList(HttpServletRequest request, UserBean userBean,
			int page, int rows) {
		// 设置每页记录数
		PageContext.getContext().setPageSize(rows);
		// 跳转到指定页
		PageContext.getContext().gotoPage(page);

		List<UserBean> userBeanList = userService.queryUser(userBean);

		Page currentPage = new Page();
		// 总行数
		int totlaRols = PageContext.getContext().getTotal();
		currentPage.setTotal(totlaRols);
		currentPage.setRows(userBeanList);

		return currentPage;
	}

	/**
	 * 不分页查询用户信息
	 * 
	 * @param userBean
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/list")
	@ResponseBody
	public List<UserBean> queryUserList(UserBean userBean) {
		return userService.queryUser(userBean);
	}

	/**
	 * 删除用户
	 * 
	 * @param userId
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public Map<String, Object> delUser(String userId) {
		boolean result = true;
		String msg = "";

		try {
			this.userService.delUserById(userId);
			msg = "删除用户成功";
		} catch (LogicException e) {
			result = false;
			msg = e.getMessage();
			logger.error("删除用户出错：" + e.getMessage());
		} catch (Exception e) {
			result = false;
			msg = "删除用户出错，系统内部错误";
			logger.error("删除用户出错：" + e);
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("result", result);
		map.put("msg", msg);

		return map;
	}

	/**
	 * 修改用户状态
	 * 
	 * @param userId
	 *            用户ID
	 * @param state
	 *            用户状态 0：启用，1：停用
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/editState")
	@ResponseBody
	public Map<String, Object> editState(String userId, String state) {

		boolean result = true;
		String msg = "";
		Map<String, Object> map = new HashMap<String, Object>();

		try {

			result = userService.editState(userId, state);
			msg = "修改用户状态成功！";

		} catch (LogicException e) {

			result = false;
			msg = e.getMessage();
			logger.error("修改用户状态出错：" + e);

		} catch (Exception e) {

			result = false;
			msg = "修改用户状态出错，系统内部错误";
			logger.error("修改用户状态出错：" + e);

		}

		map.put("result", result);
		map.put("msg", msg);

		return map;
	}

	/**
	 * 添加用户
	 * 
	 * @param userBean
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/add")
	@ResponseBody
	public Map<String, Object> addUser(UserBean userBean) {
		boolean result = true;
		String msg = "";

		try {
			String roleIds = userBean.getRoleIds();
			if (!StringTools.isNull(roleIds)) {
				String[] roleIdArr = roleIds.split(",");
				List<RoleBean> roleList = new ArrayList<RoleBean>();
				for (String roleId : roleIdArr) {
					RoleBean roleBean = new RoleBean();
					roleBean.setId(roleId);

					roleList.add(roleBean);
				}
				userBean.setRoleList(roleList);
			}

			userService.addUser(userBean);
			msg = "新增用户【" + userBean.getUserName() + "】成功";
		} catch (LogicException e) {
			result = false;
			msg = e.getMessage();
			logger.error("新增用户出错：" + e.getMessage());
		} catch (Exception e) {
			result = false;
			msg = "新增用户出错，系统内部错误";
			logger.error("新增用户出错：" + e);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("result", result);
		map.put("msg", msg);
		return map;
	}

	/**
	 * 获取用户角色 人员管理使用
	 * 
	 * @param userId
	 *            用户ID
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/userRoleList")
	@ResponseBody
	public List<RoleUserRelBean> queryUserRole(String userId) {
		List<RoleUserRelBean> userRoleList = null;
		try {
			userRoleList = roleUserRelService.queryUserRoleByUserId(userId);
		} catch (LogicException e) {
			logger.error("获取用户角色关联关系出错：" + e.getMessage());
		} catch (Exception e) {
			logger.error("获取用户角色关联关系出错：" + e);
		}

		return userRoleList;
	}

	/**
	 * 修改用户信息
	 * 
	 * @param userBean
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/edit")
	@ResponseBody
	public Map<String, Object> editUser(UserBean userBean) {
		boolean result = true;
		String msg = "";

		try {
			userService.editUser(userBean);
			msg = "修改用户【" + userBean.getUserName() + "】成功";
		} catch (LogicException e) {
			result = false;
			msg = e.getMessage();
			logger.error("修改用户出错：" + e.getMessage());
		} catch (Exception e) {
			result = false;
			msg = "修改用户出错，系统内部错误";
			logger.error("修改用户出错：" + e);
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("result", result);
		map.put("msg", msg);

		return map;
	}

	/**
	 * 医生获取选择了自己的病人信息
	 * 
	 * @param request
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/linkman/list")
	@ResponseBody
	public List<WxDoctorSelBean> queryLinkman(HttpServletRequest request,
			String openId) {

		HttpSession session = request.getSession();
		UserBean userBeans = (UserBean) session
				.getAttribute(SessionKeyContent.SESSION_KEY_OBJ_USER_BEAN);

		WxDoctorSelBean wxDoctorSelBean = new WxDoctorSelBean();
		wxDoctorSelBean.setUserId(userBeans.getId());
		wxDoctorSelBean.setOpenId(openId);
		List<WxDoctorSelBean> doctorSel = wxDoctorSelService
				.queryWxDoctorSel(wxDoctorSelBean);

		return doctorSel;
	}

	@RequestMapping("/selUser")
	@ResponseBody
	public Map<String, Object> seluser(UserBean userBean) {
		List<UserBean> list = userService.queryUser(userBean);
		UserBean user = list.get(0);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userName", user.getUserName());
		map.put("password", user.getPassword());
		return map;

	}

	/**
	 * 查询关联我的用户详细信息
	 * 
	 * @param request
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/detail/list")
	@ResponseBody
	public Page queryUserDetail(HttpServletRequest request, int page, int rows,
			UserDetailBean userDetailBean) {
		HttpSession session = request.getSession();
		UserBean userBeans = (UserBean) session
				.getAttribute(SessionKeyContent.SESSION_KEY_OBJ_USER_BEAN);

		// 设置每页记录数
		PageContext.getContext().setPageSize(rows);
		// 跳转到指定页
		PageContext.getContext().gotoPage(page);

		if (null == userDetailBean) {
			userDetailBean = new UserDetailBean();
		}

		userDetailBean.setDoctorUserId(userBeans.getId());
		List<UserDetailBean> userDetailList = userDetailService
				.queryUserDetail(userDetailBean);

		Page currentPage = new Page();
		// 总行数
		int totlaRols = PageContext.getContext().getTotal();
		currentPage.setTotal(totlaRols);
		currentPage.setRows(userDetailList);

		return currentPage;

	}

	/**
	 * 统计用户明细
	 * 
	 * @param request
	 * @param userDetailBean
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/detail/count")
	@ResponseBody
	public int countUserDetail(HttpServletRequest request,
			UserDetailBean userDetailBean) {
		HttpSession session = request.getSession();
		UserBean userBeans = (UserBean) session
				.getAttribute(SessionKeyContent.SESSION_KEY_OBJ_USER_BEAN);

		if (null == userDetailBean) {
			userDetailBean = new UserDetailBean();
		}

		userDetailBean.setDoctorUserId(userBeans.getId());

		return userDetailService.countUserDetail(userDetailBean);
	}

	/**
	 * 修改密码
	 * 
	 * @param oldPassword
	 *            原密码
	 * @param newPassword
	 *            新密码
	 * @return
	 * @throws LogicException
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/editPassord")
	@ResponseBody
	public Map<String, Object> editPassword(HttpServletRequest request,
			String oldPasswordRSA, String newPasswordRSA) {

		boolean result = true;
		String msg = "";
		Map<String, Object> map = new HashMap<String, Object>();

		// 从session中获取秘钥种子，解密加密后的密码
		HttpSession session = request.getSession();

		// 从session中获取用户信息
		UserBean userBean = (UserBean) session
				.getAttribute(SessionKeyContent.SESSION_KEY_OBJ_USER_BEAN);

		try {

			result = userService.editPassword(userBean, oldPasswordRSA,
					newPasswordRSA);
			msg = "修改密码成功！";
			// 把修改过密码的用户对象放入session中
			session.setAttribute(SessionKeyContent.SESSION_KEY_OBJ_USER_BEAN,
					userBean);

		} catch (LogicException e) {

			result = false;
			msg = e.getMessage();
			logger.error("修改密码出错：" + e.getMessage());

		} catch (Exception e) {

			result = false;
			msg = "修改密码出错，系统内部错误";
			logger.error("修改密码出错：" + e);

		}

		map.put("result", result);
		map.put("msg", msg);

		return map;
	}

	/**
	 * 页面跳转
	 * 
	 * @param pageName
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/gotoPage")
	public ModelAndView gotoPage(String pageName) {
		ModelAndView mov = new ModelAndView();
		mov.setViewName("user/" + pageName);
		return mov;
	}
}
